<?php

class Ext_Autha
{
    protected static $_instance = null;

    protected $_storage = null;

    protected function __construct()
    {}

    protected function __clone()
    {}

    public static function getInstance()
    {
        $_className = _get_called_class();
        if (!isset(self::$_instance[$_className])) {
            self::$_instance[$_className] = new $_className();
        }

        return self::$_instance[$_className];
    }

    public function getStorage()
    {
        if (null === $this->_storage) {
            require_once 'Ext/Session.php';
            $session = new Ext_Session('Zend_Auth', 'userId');
            $session->getSession()->rememberMe(365*24*60*60);
            $this->setStorage($session);
        }

        return $this->_storage;
    }

    public function setStorage(Ext_Session $storage)
    {
        $this->_storage = $storage;
        return $this;
    }

    public function auth($identity)
    {
        if ($this->hasIdentity()) {
            $this->clearIdentity();
        }

        $this->getStorage()->write($identity);
    }

    public function hasIdentity()
    {
        return !$this->getStorage()->isEmpty();
    }

    public function getIdentity()
    {
        $storage = $this->getStorage();

        if ($storage->isEmpty()) {
            return null;
        }

        return $storage->read();
    }

    public function clearIdentity()
    {
        $this->getStorage()->clear($this->getStorage()->getMember());
    }
    
    public function clear()
    {
        $this->getStorage()->clear();
    }
}
